<template>
  <div class="overflow-auto flex flex-col items-center">
    <z-svg-icon
      class="w-3 h-3 p-0.5 m-1 ml-auto"
      name="close"
      fillClass="fill-zinc-900 dark:fill-zinc-200"
      @click="close"
      v-if="isMobileTerminal"
    ></z-svg-icon>

    <img :src="blob" ref="imageTarget" />

    <z-button
      class="mt-4 w-[80%] xl:1/2"
      @click="onConfirmClick"
      :loading="loading"
      >确定</z-button
    >
  </div>
</template>

<script setup>
import { isMobileTerminal } from '@/utils/flexible'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { ref, onMounted } from 'vue'
import { getOSSClient } from '@/utils/sts'
import { useUserStore } from '@/store/modules/user'
import { storeToRefs } from 'pinia'
import { message } from '@/libs/message'
import { putProfile } from '@/api/sys'

defineProps({
  blob: {
    type: String,
    required: true
  }
})

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const emits = defineEmits(['close'])
const loading = ref(false)

const close = () => {
  emits('close')
}

/**
 * 确认裁剪
 */
const onConfirmClick = () => {
  loading.value = true
  const canvas = cropper.getCroppedCanvas()
  canvas.toBlob((blob) => {
    putObjectToOSS(blob)
  })
}

/**
 * 进行oss上传
 */
let ossClient = null
const putObjectToOSS = async (file) => {
  if (!ossClient) {
    ossClient = await getOSSClient()
  }
  try {
    const fileArray = file.type.split('/')
    const fileName = `${userInfo.value.username}/${Date.now()}.${
      fileArray[fileArray.length - 1]
    }`
    const res = await ossClient.put(`images/${fileName}`, file)
    onChangeProfile(res.url)
  } catch (error) {
    message('error', '上传失败')
  }
}

/**
 * 上传文件到服务器
 */
const onChangeProfile = async (avatar) => {
  // 更新本地数据
  userStore.setUserInfo({
    ...userInfo.value,
    avatar
  })
  const data = await putProfile(userInfo.value)
  message('success', '用户头像修改成功')
  loading.value = false
  close()
}

/**
 * 图片裁剪
 */
const imageTarget = ref(null)
let cropper = null

// 裁剪参数
const pcOptions = {
  aspectRatio: 1
}
const mobileOptions = {
  aspectRatio: 1,
  viewMode: 1,
  dragMode: 'move',
  cropBoxMovable: false,
  cropBoxResizable: false
}

onMounted(() => {
  cropper = new Cropper(
    imageTarget.value,
    isMobileTerminal.value ? mobileOptions : pcOptions
  )
})
</script>

<style lang="scss" scoped></style>
